package git.bds.nyc.applet.api.service.attestation;


import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import git.bds.nyc.applet.api.convert.AttestationConvert;
import git.bds.nyc.applet.api.model.dto.FarmerAuthenticationInfoDTO;
import git.bds.nyc.exception.BusinessException;
import git.bds.nyc.framework.file.minio.MinioConfig;
import git.bds.nyc.framework.file.minio.MinioUtil;
import git.bds.nyc.result.ResultCode;
import git.bds.nyc.role.domain.authentication.FarmerAuthentication;
import git.bds.nyc.role.mapper.mp.SysUserRoleMapper;
import git.bds.nyc.role.mapper.mp.authentication.FarmerAuthenticationMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 成大事
 * @since 2023/3/11 17:41
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class AttestationServiceImpl implements AttestationService{

    private final FarmerAuthenticationMapper farmerAuthenticationMapper;

    private final SysUserRoleMapper sysUserRoleMapper;

    private final MinioUtil minioUtil;

    private final MinioConfig minioConfig;

    /**
     * 农民身份验证
     *
     * @param infoDTO 信息发送到
     * @return {@link Boolean}
     */
    @Override
    @SneakyThrows
    public Boolean farmerAuthentication(FarmerAuthenticationInfoDTO infoDTO) {
        long userId = StpUtil.getLoginIdAsLong();
        log.info("infoDTO:  "+infoDTO);
        try {
            FarmerAuthentication farmerAuthentication = AttestationConvert.INSTANCE.toFarmerAuthentication(infoDTO, userId,infoDTO.getFrontImg(),infoDTO.getBackImg());
            return  farmerAuthenticationMapper.insert(farmerAuthentication) > 0;
        } catch (Exception e) {
            minioUtil.removeFile(minioConfig.getBucketName(),infoDTO.getFrontImg());
            minioUtil.removeFile(minioConfig.getBucketName(),infoDTO.getBackImg());
            throw new BusinessException(ResultCode.ID_CARD_INFO_ERROR.getCode(),ResultCode.ID_CARD_INFO_ERROR.getMessage());
        }

    }

    /**
     * 是农民身份验证吗
     *
     * @return {@link Boolean}
     */
    @Override
    public Boolean isFarmerAuthentication() {
        FarmerAuthentication one = farmerAuthenticationMapper.selectOne(new LambdaQueryWrapper<FarmerAuthentication>()
                .select(FarmerAuthentication::getId)
                .eq(FarmerAuthentication::getUserId, StpUtil.getLoginIdAsLong()));
        return one != null;
    }
}
